import { _decorator, Component, Node, Sprite, SpriteFrame } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('SlotMachine')
export class SlotMachine extends Component {

    
    @property([Sprite])
    images: SpriteFrame[] = []; // 图片数组

    @property([Sprite])
    spriteList: Sprite[] = []; // 存储三张图片的 Sprite 组件

    @property
    spinDuration: number = 2; // 动画持续时间

    private isSpinning: boolean = false;

    // 在组件加载时展示随机的三张图片
    onLoad() {
        this.displayRandomImages();
    }

    // 显示随机三张图片
    private displayRandomImages() {
        const usedIndices = new Set<number>();
        while (usedIndices.size < 3 && usedIndices.size < this.images.length) {
            const randomIndex = Math.floor(Math.random() * this.images.length);
            usedIndices.add(randomIndex);
        }
        
        const indicesArray = Array.from(usedIndices);
        for (let i = 0; i < this.spriteList.length; i++) {
            if (i < indicesArray.length) {
                this.spriteList[i].spriteFrame = this.images[indicesArray[i]];
            }
        }
    }

    // 开始旋转
    startSpin() {
        this.isSpinning = true;
        this.schedule(this.spin, 0.1); // 每0.1秒更新一次显示的图片
        this.scheduleOnce(this.stopSpin, this.spinDuration); // 设置停止时间
    }

    // 旋转图片显示
    private spin() {
        if (this.isSpinning) {
            this.spriteList.forEach(sprite => {
                const randomIndex = Math.floor(Math.random() * this.images.length);
                sprite.spriteFrame = this.images[randomIndex];
            });
        }
    }

    // 停止旋转
    private stopSpin() {
        this.isSpinning = false;
        // 随机选择最终显示的图片
        this.spriteList.forEach(sprite => {
            const finalIndex = Math.floor(Math.random() * this.images.length);
            sprite.spriteFrame = this.images[finalIndex];
        });
    }
   

    start() {

    }

    update(deltaTime: number) {
        
    }
}

